/** TS AST 分析 */
import * as ts from 'typescript';
import * as fs from 'fs';
import * as path from 'path';

// 用于存储接口定义
interface InterfaceDefinition {
  jsDoc?: {
    description?: string;
    tags: Record<string, string>;
  };
  properties: Record<string, {
    type: string;
    optional?: boolean;  // 新增字段，表示属性是否可选
    jsDoc?: {
      description?: string;
      tags: Record<string, string>;
    };
  }>;
  extends?: string[];
}

const interfaces: Record<string, InterfaceDefinition> = {};

// 获取所有.d.ts文件
function getAllTypeFiles(directory: string): string[] {
  return fs.readdirSync(directory)
    .filter(file => file.endsWith('.ts'))
    .map(file => path.join(directory, file));
}

// 解析JSDoc注释
function parseJSDoc(node: ts.Node): { description?: string; tags: Record<string, string> } {
  const jsDocTags: Record<string, string> = {};
  const jsDoc = (node as any).jsDoc?.[0];

  if (!jsDoc) return { tags: {} };

  // 获取描述
  const description = jsDoc.comment?.toString();

  // 获取标签
  if (jsDoc.tags) {
    jsDoc.tags.forEach((tag: any) => {
      const tagName = tag.tagName.text;
      const comment = tag.comment?.toString() || '';
      jsDocTags[tagName] = comment;
    });
  }

  return {
    description,
    tags: jsDocTags
  };
}

// 处理单个文件
function processFile(filePath: string) {
  const sourceCode = fs.readFileSync(filePath, 'utf-8');
  const sourceFile = ts.createSourceFile(
    path.basename(filePath),
    sourceCode,
    ts.ScriptTarget.Latest,
    true
  );

  // 递归遍历AST并生成类型定义
  function visit(node: ts.Node) {
    if (ts.isInterfaceDeclaration(node)) {
      const interfaceName = node.name.text;
      const properties: InterfaceDefinition['properties'] = {};
      const jsDoc = parseJSDoc(node);

      // 处理继承
      const extendsClause = node.heritageClauses?.find(clause =>
        clause.token === ts.SyntaxKind.ExtendsKeyword
      );
      const extendsList = extendsClause?.types.map(type => type.expression.getText(sourceFile));

      node.members.forEach(member => {
        if (ts.isPropertySignature(member)) {
          const propertyName = member.name.getText(sourceFile);
          const propertyType = member.type?.getText(sourceFile);
          if (propertyName !== undefined && propertyType !== undefined) {
            properties[propertyName] = {
              type: propertyType,
              optional: member.questionToken !== undefined,  // 检查是否有问号标记
              jsDoc: parseJSDoc(member)
            };
          }
        }
      });

      interfaces[interfaceName] = {
        jsDoc,
        properties,
        extends: extendsList
      };
    }

    node.forEachChild(visit);
  }

  visit(sourceFile);
}

// 格式化输出函数
function formatInterface(name: string, def: InterfaceDefinition, indent = 0): string {
  const indentStr = ' '.repeat(indent);
  const lines: string[] = [];

  // 添加JSDoc注释
  if (def.jsDoc) {
    lines.push(`${indentStr}/**`);
    if (def.jsDoc.description) {
      lines.push(`${indentStr} * ${def.jsDoc.description}`);
    }
    Object.entries(def.jsDoc.tags).forEach(([tag, value]) => {
      lines.push(`${indentStr} * @${tag} ${value}`);
    });
    lines.push(`${indentStr} */`);
  }

  // 添加接口声明
  const extendsClause = def.extends?.length
    ? ` extends ${def.extends.join(', ')}`
    : '';
  lines.push(`${indentStr}interface ${name}${extendsClause} {`);

  // 添加属性
  Object.entries(def.properties).forEach(([propName, prop]) => {
    // 属性的JSDoc
    if (prop.jsDoc) {
      lines.push(`${indentStr}  /**`);
      if (prop.jsDoc.description) {
        lines.push(`${indentStr}  * ${prop.jsDoc.description}`);
      }
      Object.entries(prop.jsDoc.tags).forEach(([tag, value]) => {
        lines.push(`${indentStr}  * @${tag} ${value}`);
      });
      lines.push(`${indentStr}  */`);
    }
    lines.push(`${indentStr}  ${propName}${prop.optional ? '?' : ''}: ${prop.type};`);
  });

  lines.push(`${indentStr}}`);
  return lines.join('\n');
}

// 主程序
const typesDir = path.join(__dirname, '../../models/types');
const typeFiles = getAllTypeFiles(typesDir);

// 处理所有类型文件
typeFiles.forEach(file => {
  // console.log(`Processing: ${path.basename(file)}`);
  processFile(file);
});

// 输出所有接口定义
// console.log('\nType Definitions:');
// console.log('=================\n');

// console.time('Output');
// Object.entries(interfaces).forEach(([name, def]) => {
//   console.log(formatInterface(name, def));
//   console.log();
// });
// console.timeEnd('Output');

export const buildInterfaceCode = () => {
  let interfaceCode = '';
  Object.entries(interfaces).forEach(([name, def]) => {
    interfaceCode += formatInterface(name, def);
    interfaceCode += '\n\n';
  });
  return interfaceCode
}